package com.tutu.sys.controller;

import java.io.File;
import java.io.IOException;
import java.util.ResourceBundle;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.tutu.common.GlobalConstants;
import com.tutu.sys.entity.SysFile;
import com.tutu.sys.service.ISysFileService;

@Controller
@RequestMapping("/file")
public class FileAction {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Resource
	private ISysFileService sysFileService;
	
	@RequestMapping("/downloadFile")
	public ResponseEntity<byte[]> downloadFile(@RequestParam String fileId){
		ResourceBundle resourceBundle = ResourceBundle.getBundle("common");
		String fileStorePath = resourceBundle.getString(GlobalConstants.FILE_STORE_PATH);
		if(!fileStorePath.endsWith(File.separator)){
			fileStorePath += File.separator;
		}
		ResponseEntity<byte[]> responseEntity = null;
		SysFile sysFile = this.sysFileService.getSysFileById(fileId);
		if(null==sysFile)
			return responseEntity;
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", sysFile.getFileName());
		File file = FileUtils.getFile(fileStorePath+sysFile.getFilePath());
		try {
			responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
		} catch (IOException e) {
			logger.error("查看文件", e);
		}
		return responseEntity;
	}

}
